const jwt = require('jsonwebtoken');
const config = require('../config');
const db = require('../db/index');
const fs = require('fs');
const path = require('path');

module.exports = {
    vertoken(tokenStr) {
        return new Promise((resolve, reject) => {
            jwt.verify(tokenStr, config.jwtSecretKey, (err, decoded) => {
                if (err) {
                    // JWT 验证失败
                    console.error(err);
                    reject('Invalid token'); // 返回错误消息
                }

                const { uid } = decoded;
                resolve(uid); // 返回解析出的 uid
            });
        });
    },
    async getUserInfo(req, res) {
        return new Promise((resolve, reject) => {
            try {
                let user = req.user.uid;
                let sql =
                    "SELECT id,name,status,roles_id AS rolesId,admin,url FROM user WHERE id=?";
                db.query(sql, user, (err, results) => {
                    if (err) return reject(err);
                    if (results.length == 0) return reject('用户不存在');
                    resolve(results[0]);
                });
            } catch (error) {
                console.error(error);
                reject(error);
            }
        });
    },
    async getUserRole(req, res) {
        return new Promise(async (resolve, reject) => {
            let user = await this.getUserInfo(req, res)
            let sql = "SELECT roles,role_key FROM roles WHERE FIND_IN_SET(id,?)";
            db.query(sql, [user.rolesId], (err, results) => {
                if (err) return res.cc(err)
                if (results.length == 0) return res.cc('获取权限失败')
                let roles = results.map(t => t.roles);
                let roleKey = results.map(t => t.role_key);
                let roleAdmin = roleKey.some(t => t === "admin");
                resolve({ userRole: roles.join(","), roleKey, user, roleAdmin });
            })
        })
    },
    /**
    * 分页页码处理
    * @param sql  sql语句
    * @param page  页码
    * @param size  最大数量
    * */
    pageSize(sql, page, size) {
        if (!page) { page = 1 };
        if (!size) { size = 10 };
        page = (page - 1) * size;
        size = parseInt(size);
        return sql += ` LIMIT ${page},${size}`;
    },
    /**
     * 查询总数
     * @param sql  sql语句
     * @param name  表名
     * @param res  响应主体
     * @param req  请求主体
     * */
    async getSum({ sql = "", name, res, req }) {
        const regex = /WHERE(.+)/;
        const result = sql.match(regex);
        let where = "1=1";
        if (result && result[1]) where = result[1].trim();
        let sqlRes = `SELECT count(1) FROM ${name} WHERE ${where}`;
        /*  let { result: resultRes } = await this.poolsEvent()({ sql: sqlRes, res, req }); */
        let resultRes = await new Promise((resolve, reject) => {
            db.query(sql, (err, results) => {
                if (err) return res.cc(err)
                resolve(results)
            })
        })
        
        return { total: resultRes.length };
    },
    setLike(sql, name = "", val = "") {
        if (this.exist(val)) sql += ` AND ${name} LIKE "%${val}%"`;
        return sql
    },
    /**
   * 判断是否为空
   * @param str any
   * */
    exist(str) {
        return str !== undefined && str !== "" && str !== null;
    },
    async existName({ sql, name, msg = "名称已存在！", req, res }) {
        if (!name) return true;
        try {
            const result = await new Promise((resolve, reject) => {
                db.query(sql, name, (err, results) => {
                    if (err) return reject(err);
                    resolve(results);
                });
            });
            if (result.length > 0) {
                return res.send({ code: 500, msg: '名称已存在' });
            } else {
                return true;
            }
        } catch (err) {
            return res.cc(err);
        }
    },
    async judgeUserName({ sql, sqlName = "name", name, id, req, res }) {
        let result = await new Promise((resolve, reject) => {
            db.query(sql, id, (err, results) => {
                if (err) return res.cc(err)
                resolve(results)
            })
        })
        if (result[0][sqlName] == name) return -1
        return 1
    },
  async  delPreImg({id,name,obj}) {
        let delSql = `select url from ${name} where id=?`;
        let delPath = await new Promise((resolve, reject) => {
            db.query(delSql, id, (err, results) => {
                if (err) return res.cc(err);
                const url = results[0].url;
                // 提取图片文件名
                const fileName = url.split('/').pop();
                resolve({fileName,url});
            });
        });
        if (obj.url !== delPath.url) {
            const fileName = delPath.fileName.split('/').pop();
            const filePath = path.join(__dirname, '..', 'public', fileName);
            fs.unlink(filePath, (err) => {
                if (err) {
                    console.error(err);
                }
            });
        }
    }
};